/*
 * @Author: huangyq
 * @Date: 2022-04-06 13:06:32
 * @LastEditTime: 2022-06-14 14:13:44
 * @LastEditors: huangyq
 * @Description: http实例
 * @FilePath: /vue3-boilerplate-pc-client/src/plugins/httpHelper/instance/HttpInstance.ts
 */
import axios, {
  AxiosInstance,
  AxiosRequestHeaders,
  AxiosRequestConfig
} from 'axios'
import {
  requestFailedInterceptor,
  requestSuccessInterceptor,
  responseFailedInterceptor,
  responseSuccessInterceptor
} from './HttpInterceptors'

let httpInstance: AxiosInstance | null = null

export interface IInstanceOpt {
  baseURL: string
  headers?: AxiosRequestHeaders
  toast: (code: string, message: string) => void
  responseTokenHandler: (code: string) => void
  requestTokenHandler: (request: AxiosRequestConfig) => void
  requestPermissionHandler: (request: AxiosRequestConfig) => void
}

/**
 * 创建http实例
 * @param opt
 * @returns
 */
export function createHttpInstance(options: IInstanceOpt) {
  const {
    baseURL,
    headers,
    toast,
    responseTokenHandler,
    requestTokenHandler,
    requestPermissionHandler
  } = options
  if (!httpInstance) {
    httpInstance = axios.create({
      baseURL: baseURL,
      withCredentials: false,
      headers: headers
    })
  }
  httpInstance.interceptors.request.use((request: unknown) => {
    return requestSuccessInterceptor(
      request,
      requestTokenHandler,
      requestPermissionHandler
    )
  }, requestFailedInterceptor)
  httpInstance.interceptors.response.use(
    (response: unknown) => {
      return responseSuccessInterceptor(response, toast, responseTokenHandler)
    },
    (error: unknown) => {
      return responseFailedInterceptor(error, toast)
    }
  )
  return httpInstance
}
